package com.ylr.blog.common.algorithm;

import com.ylr.base.common.exception.YlrException;
import org.apache.shardingsphere.sharding.api.sharding.complex.ComplexKeysShardingAlgorithm;
import org.apache.shardingsphere.sharding.api.sharding.complex.ComplexKeysShardingValue;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.*;

/**
 * Created by IntelliJ IDEA.
 *
 * @author wyw
 * date: 2023-06-09 21:13:55
 * className: BlogTableComplexShardingAlgorithm
 * version: 1.0
 * description:
 */
public class BlogTableComplexShardingAlgorithm implements ComplexKeysShardingAlgorithm<String> {

    private static final Logger log = LoggerFactory.getLogger(BlogTableComplexShardingAlgorithm.class);

    /**
     * 表字段名称
     */
    private static final String ID = "id";

    /**
     * 表字段名称
     */
    private static final String CODE = "code";

    @Override
    public Collection<String> doSharding(Collection<String> collection, ComplexKeysShardingValue<String> complexKeysShardingValue) {

        List<String> tableNameList = new ArrayList<>();
        // 逻辑表名
        StringBuilder sb = new StringBuilder(complexKeysShardingValue.getLogicTableName());
        int length = complexKeysShardingValue.getLogicTableName().length();

        Map<String, Collection<String>> columnNameAndShardingValuesMap = complexKeysShardingValue.getColumnNameAndShardingValuesMap();
        // 获取sql携带的主键值列表
        Collection<String> idList = columnNameAndShardingValuesMap.getOrDefault(ID, Collections.emptyList());
        for (String id : idList) {
            // 取后两位数字
            long _userId = Long.parseLong(id.substring(id.length() - 1));
            // 求余
            String suffix = String.valueOf(_userId % 2);
            // 补全表名称
            sb.replace(length, length + suffix.length(), suffix);
            // 记录
            tableNameList.add(sb.toString());
        }
        // 获取sql携带的博客编号值列表
        Collection<String> codeList = columnNameAndShardingValuesMap.getOrDefault(CODE, Collections.emptyList());
        for (String code : codeList) {
            // 取‘博客编号’中存储的‘博客基因’后两位数字
            long _idSuffix = Long.parseLong(code.substring(6, 8));
            // 求余
            String suffix = String.valueOf(_idSuffix % 2);
            // 补全表名称
            sb.replace(length, length + suffix.length(), suffix);
            // 记录
            tableNameList.add(sb.toString());
        }
        if (tableNameList.isEmpty()) {
            log.error("计算得到的表列表为空。db={} userIdList={} codeList={}", complexKeysShardingValue.getLogicTableName(), idList, codeList);
            throw new YlrException();
        }
        return tableNameList;
    }

    @Override
    public void init() {

    }

    @Override
    public String getType() {
        return "COMPLEX";
    }
}
